package com.stable.spider.eastmoney;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stable.utils.DateUtil;
import com.stable.utils.HttpUtil;
import com.stable.vo.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Log4j2
public class EastMoneySpider {

    /**
     * 格式化成东方财富 API所需格式
     */
    public static String formatCode(String code) {
        // 5开头，沪市基金或权证 60开头上证
        if (code.startsWith("6")) {
            return String.format("SH%s", code);
        } else if (code.startsWith("0")) {
            return String.format("SZ%s", code);
        } else if (code.matches("^60.*|^5.*")) {
            return String.format("SH%s", code);
        }
        // 1开头的，是深市基金 00开头是深圳
        else if (code.matches("^1.*|^00.*|^300...")) {
            return String.format("SZ%s", code);
        }
        return null;
    }

    /**
     * 格式化成东方财富 secid API所需格式
     */
    public static String formatSecid(String code) {
        // 5开头，沪市基金或权证 60开头上证
        if (code.startsWith("6")) {
            return String.format("1.%s", code);
        } else if (code.startsWith("0")) {
            return String.format("0.%s", code);
        } else if (code.matches("^60.*|^5.*")) {
            return String.format("1.%s", code);
        }
        // 1开头的，是深市基金 00开头是深圳
        else if (code.matches("^1.*|^00.*|^300...")) {
            return String.format("0.%s", code);
        }
        return null;
    }

    /**
     * 获取概念信息
     *
     * @param code 6位普通股票代码
     * @return http://f10.eastmoney.com/CoreConception/CoreConceptionAjax?code=SZ300021
     */
    public String getCoreConception(String code) {
        String coreConceptionUrl = "http://f10.eastmoney.com/CoreConception/CoreConceptionAjax?code=%s";
        String url = String.format(coreConceptionUrl, formatCode(code));
        JSONObject jsonObject = HttpUtil.doGet(url);
        JSONArray hxtc = jsonObject.getJSONArray("hxtc");
        if (hxtc.size() > 0) {
            JSONObject jsonObject1 = hxtc.getJSONObject(0);
            if (jsonObject1.size() > 0) {
                return jsonObject1.get("ydnr").toString();
            }
        }
        return "";
    }


    /**
     * 行业排行
     *
     * @param code 6位普通股票代码
     * @return http://f10.eastmoney.com/IndustryAnalysis/IndustryAnalysisAjax?code=SZ002417&icode=737
     */
    public IndustryAnalysis getIndustryAnalysis(String code) {
        IndustryAnalysis industryAnalysis = new IndustryAnalysis(code);
        String coreConceptionUrl = "http://f10.eastmoney.com/IndustryAnalysis/IndustryAnalysisAjax?code=%s&icode=737";
        String url = String.format(coreConceptionUrl, formatCode(code));
        JSONObject jsonObject = HttpUtil.doGet(url);
        if (jsonObject.size() > 0) {
            //成长性比较
            JSONObject czxbj = jsonObject.getJSONObject("czxbj");
            if (czxbj.size() > 0) {
                JSONArray data = czxbj.getJSONArray("data");
                if (data.size() > 0) {
                    JSONObject jsonObject1 = data.getJSONObject(0);
                    String pm = jsonObject1.get("pm").toString();   //排名
                    String jbmgsyzzlfh = jsonObject1.get("jbmgsyzzlfh").toString(); //3年复合(基本每股收益增长率(%))
                    log.info("code:{},成长性比较, 排名:{}, 3年复合(基本每股收益增长率(%)):{}", code, pm, jbmgsyzzlfh);
                    industryAnalysis.setCzxbj_pm(pm);
                    industryAnalysis.setCzxbj_jbmgsyzzlfh(jbmgsyzzlfh);
                }
            }


            //估值比较
            JSONObject gzbj = jsonObject.getJSONObject("gzbj");
            if (gzbj.size() > 0) {
                JSONArray data = gzbj.getJSONArray("data");
                if (data.size() > 0) {
                    JSONObject jsonObject1 = data.getJSONObject(0);
                    String pm = jsonObject1.get("pm").toString();   //排名
                    String peg = jsonObject1.get("peg").toString(); //ROE(%)
                    log.info("code:{},估值比较, 排名:{}, ROE(%):{}", code, pm, peg);
                    industryAnalysis.setGzbj_pm(pm);
                    industryAnalysis.setGzbj_peg(peg);
                }
            }


            //杜邦分析比较
            JSONObject dbfxbj = jsonObject.getJSONObject("dbfxbj");
            if (dbfxbj.size() > 0) {
                JSONArray data = dbfxbj.getJSONArray("data");
                if (data.size() > 0) {
                    JSONObject jsonObject1 = data.getJSONObject(0);
                    String pm = jsonObject1.get("pm").toString();   //排名
                    String roepj = jsonObject1.get("roepj").toString(); //ROE(%)
                    log.info("code:{},杜邦分析比较, 排名:{}, ROE(%):{}", code, pm, roepj);
                    industryAnalysis.setDbfxbj_pm(pm);
                    industryAnalysis.setDbfxbj_roepj(roepj);
                }
            }

            //公司规模
            JSONArray gsgmzsz = jsonObject.getJSONArray("gsgmzsz");
            if (gsgmzsz.size() > 0) {
                JSONObject jsonObject1 = gsgmzsz.getJSONObject(0);
                String pm = jsonObject1.get("pm").toString();   //排名
                String zsz = jsonObject1.get("zsz").toString();   //总市值(元)
                log.info("code:{},公司规模, 排名:{}, 总市值(元):{}", code, pm, zsz);
                industryAnalysis.setGsgmzsz_pm(pm);
                industryAnalysis.setGsgmzsz_zsz(zsz);
            }
        }
        return industryAnalysis;
    }


    /**
     * 财务信息
     *
     * @param code 6位普通股票代码
     * @param type 0按报告期、1=年报
     * @return http://f10.eastmoney.com/NewFinanceAnalysis/MainTargetAjax?type=1&code=SZ300750
     */
    public List<NewFinanceAnalysis> getNewFinanceAnalysis(String code, int type) {
        List<NewFinanceAnalysis> list = new ArrayList<>();
        String financeUrl = "http://f10.eastmoney.com/NewFinanceAnalysis/MainTargetAjax?type=" + type + "&code=%s";
        String url = String.format(financeUrl, formatCode(code));
        String result = HttpUtil.doGet2(url);
        JSONArray objects = JSON.parseArray(result);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject data = objects.getJSONObject(i);
            String date = data.get("date").toString();                      //年报日期
            String yyzsrtbzz = data.get("yyzsrtbzz").toString();            //营业总收入同比增长(%)
            String gsjlrtbzz = data.get("gsjlrtbzz").toString();            //归属净利润同比增长(%)
            String kfjlrtbzz = data.get("kfjlrtbzz").toString();            //扣非净利润同比增长(%)
            String jqjzcsyl = data.get("jqjzcsyl").toString();              //加权净资产收益率(%)
            String mll = data.get("mll").toString();                        //毛利率(%)
            String jll = data.get("jll").toString();                        //净利率(%)
            String xsxjlyysr = data.get("xsxjlyysr").toString();            //销售现金流/营业收入
            String zcfzl = data.get("zcfzl").toString();                    //资产负债率(%)
            NewFinanceAnalysis newFinanceAnalysis = new NewFinanceAnalysis(code);
            newFinanceAnalysis.setDate(date);
            newFinanceAnalysis.setType(type);
            newFinanceAnalysis.setYyzsrtbzz(yyzsrtbzz);
            newFinanceAnalysis.setGsjlrtbzz(gsjlrtbzz);
            newFinanceAnalysis.setKfjlrtbzz(kfjlrtbzz);
            newFinanceAnalysis.setJqjzcsyl(jqjzcsyl);
            newFinanceAnalysis.setMll(mll);
            newFinanceAnalysis.setJll(jll);
            newFinanceAnalysis.setXsxjlyysr(xsxjlyysr);
            newFinanceAnalysis.setZcfzl(zcfzl);
            list.add(newFinanceAnalysis);
        }
        return list;
    }


    /**
     * 预测指标   归属于母公司股东的净利润(元)
     * http://f10.eastmoney.com/ProfitForecast/Index?type=web&code=SZ000651#
     *
     * @param code 6位普通股票代码
     * @return http://f10.eastmoney.com/ProfitForecast/ProfitForecastAjax?code=SZ000651
     */
    public List<ProfitForecast> getProfitForecast(String code) {
        List<ProfitForecast> list = new ArrayList<>();
        String financeUrl = "http://f10.eastmoney.com/ProfitForecast/ProfitForecastAjax?code=%s";
        String url = String.format(financeUrl, formatCode(code));
        String result = HttpUtil.doGet2(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray objects = jsonObject.getJSONObject("yctj").getJSONArray("data");
        for (int i = 0; i < objects.size(); i++) {
            JSONObject data = objects.getJSONObject(i);
            String rq = data.get("rq").toString();                        //年报日期
            String mgsy = data.get("mgsy").toString();                 //每股收益(元)
            String mgjzc = data.get("mgjzc").toString();                //每股净资产(元)
            String jzcsyl = data.get("jzcsyl").toString();               //净资产收益率(%)
            String jlr = data.get("jlr").toString();                   //归属于母公司股东的净利润(元)
            String yyzsr = data.get("yyzsr").toString();                      //营业总收入(元)
            String yylr = data.get("yylr").toString();                       //营业利润(元)
            ProfitForecast profitForecast = new ProfitForecast(code);
            profitForecast.setRq(rq);
            profitForecast.setMgsy(mgsy);
            profitForecast.setMgjzc(mgjzc);
            profitForecast.setJzcsyl(jzcsyl);
            profitForecast.setJlr(jlr);
            profitForecast.setYyzsr(yyzsr);
            profitForecast.setYylr(yylr);

            list.add(profitForecast);
        }
        return list;
    }


    /**
     * 总股本： 亿
     * http://f10.eastmoney.com/CapitalStockStructure/Index?type=web&code=SZ000651#
     *
     * @param code 6位普通股票代码
     * @return http://f10.eastmoney.com/CapitalStockStructure/CapitalStockStructureAjax?code=SZ000651
     */
    public Double getCapitalStockStructure(String code) {
        List<ProfitForecast> list = new ArrayList<>();
        String financeUrl = "http://f10.eastmoney.com/CapitalStockStructure/CapitalStockStructureAjax?code=%s";
        String url = String.format(financeUrl, formatCode(code));
        String result = HttpUtil.doGet2(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String zgb = jsonObject.getJSONObject("CapitalStockStructureDetail").get("zgb").toString();
        return Double.parseDouble(zgb.replaceAll(",", "")) / 10000;
    }


    /**
     * 历年分红数据
     * http://f10.eastmoney.com/BonusFinancing/Index?type=web&code=SZ000651#
     *
     * @param code 6位普通股票代码
     * @return http://f10.eastmoney.com/BonusFinancing/BonusFinancingAjax?code=SZ000651
     */
    public List<BonusFinancing> getBonusFinancing(String code) {
        List<BonusFinancing> list = new ArrayList<>();
        String financeUrl = "http://f10.eastmoney.com/BonusFinancing/BonusFinancingAjax?code=%s";
        String url = String.format(financeUrl, formatCode(code));
        String result = HttpUtil.doGet2(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray objects = jsonObject.getJSONArray("lnfhrz");
        for (int i = 0; i < objects.size(); i++) {
            JSONObject data = objects.getJSONObject(i);
            String sj = data.get("sj").toString();                        //时间
            String fhze = data.get("fhze").toString().replaceAll(",", "");                    //分红总额(万元)
            BonusFinancing bonusFinancing = new BonusFinancing(code);
            bonusFinancing.setSj(sj);
            bonusFinancing.setMgsy(fhze);
            list.add(bonusFinancing);
        }
        return list;
    }

    /**
     * 股票基础数据
     * <p>
     * http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292&secid=0.000766&cb=jQuery112405904104448962095_1592092758938&_=1592092758949
     * http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292&secid=1.603000&cb=jQuery1124040910677850217936_1592093170628&_=1592093170655
     *
     * @param code 6位普通股票代码
     * @return http://quote.eastmoney.com/sh603000.html
     */
    public EastBasic getBasicInfo(String code) {
        List<ProfitForecast> list = new ArrayList<>();
        String basicUrl = "http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292&secid=%s";
        String url = String.format(basicUrl, formatSecid(code));
        String result = HttpUtil.doGet2(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject data = jsonObject.getJSONObject("data");

        EastBasic eastBasic = new EastBasic();
        eastBasic.setCode(data.get("f57").toString());
        eastBasic.setName(data.get("f58").toString());
        eastBasic.setPrice(data.get("f43").toString());
        eastBasic.setArea_board(data.get("f128").toString());
        eastBasic.setTrade_board(data.get("f127").toString());
        eastBasic.setMgsy(data.get("f55").toString());
        eastBasic.setJzc(data.get("f92").toString());
        eastBasic.setPe(data.get("f162").toString());
        eastBasic.setPb(data.get("f167").toString());
        eastBasic.setZgb(data.get("f84").toString());
        eastBasic.setZz(data.get("f116").toString());
        eastBasic.setLtg(data.get("f85").toString());
        eastBasic.setLz(data.get("f117").toString());

        return eastBasic;
    }


    /**
     * 获取pe pb估值数据
     * http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=GZFX_GGZB&token=894050c76af8597a853f5b408b759f5d&st=SECURITYCODE&sr=1&p=1&ps=50&js=var%20RBhhxNnd={pages:(tp),data:(x),font:(font)}&filter=(TRADEDATE=^2020-06-05^)&rt=53050606
     * http://data.eastmoney.com/gzfx/list.html
     *
     * @return
     */
    public List<EastBasicExt> getGUZHIInfo(int page, String datetime) throws Exception {
        String basicUrl = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=GZFX_GGZB&token=894050c76af8597a853f5b408b759f5d&st=SECURITYCODE&sr=1&p=" + page + "&ps=50&filter=(TRADEDATE='"+datetime+"')";
        String url = basicUrl.replace("(","%28").replace(")","%29");
        String result = HttpUtil.doGet2(url);

        List<EastBasicExt> list = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(result);
        for (int i = 0; i < array.size(); i++) {
            EastBasicExt ext = new EastBasicExt();
            JSONObject jsonObject = array.getJSONObject(i);
            ext.setCode(jsonObject.getString("SECURITYCODE"));
            ext.setName(jsonObject.getString("SName"));
            ext.setPettm(jsonObject.getString("PE9"));
            ext.setPe(jsonObject.getString("PE7"));
            ext.setPb(jsonObject.getString("PB8"));
            ext.setPeg1(jsonObject.getString("PEG1"));
            ext.setSxiaol(jsonObject.getString("PS9"));
            ext.setSxianl(jsonObject.getString("PCFJYXJL9"));
            ext.setSshy(jsonObject.getString("HYName"));
            ext.setZsz(jsonObject.getString("ZSZ"));
            ext.setLtsz(jsonObject.getString("AGSZBHXS"));
            ext.setZgb(jsonObject.getString("ZGB"));
            ext.setLtgb(jsonObject.getString("LTAG"));
            list.add(ext);
        }
        return list;
    }

    public static void main(String[] args) throws Exception {
        EastMoneySpider moneySpider = new EastMoneySpider();
//        System.out.println(moneySpider.getIndustryAnalysis("601007"));
//        System.out.println(moneySpider.getIndustryAnalysis("600021"));
//        System.out.println(moneySpider.getIndustryAnalysis("603099"));
//        System.out.println(moneySpider.getNewFinanceAnalysis("300570", 1));

//        moneySpider.getBasicInfo("000002");
        moneySpider.getGUZHIInfo(1, DateUtil.convertDate(DateUtil.getTodayYYYYMMDD()) );
//        System.out.println(moneySpider.getProfitForecast("000651"));
    }
}
